package cn.xiaopengstack.trigger.http;

import cn.xiaopengstack.api.dto.CreatePayOrderRequestDTO;
import cn.xiaopengstack.api.service.IPayService;
import cn.xiaopengstack.domain.order.model.entity.PayOrderEntity;
import cn.xiaopengstack.domain.order.model.entity.ShopCarEntity;
import cn.xiaopengstack.domain.order.service.IOrderService;
import cn.xiaopengstack.domain.pay.factory.PayServiceFactory;
import cn.xiaopengstack.domain.pay.model.entity.CreatePayEntity;
import cn.xiaopengstack.domain.pay.model.entity.CreatePayReqEntity;
import cn.xiaopengstack.response.Response;
import cn.xiaopengstack.types.enums.PayChannelEnum;
import cn.xiaopengstack.types.enums.ResponseCode;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Optional;

/**
 * @author jiangyangang
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/alipay/")
@CrossOrigin("*")
public class AlipayOrderController implements IPayService {

    @Value("${alipay.alipay_public_key}")
    private String alipayPublicKey;

    @Resource
    private IOrderService orderService;


    @Resource
    private PayServiceFactory payServiceFactory;

    @RequestMapping(value = "create_pay_order", method = RequestMethod.POST)
    @Override
    public Response<String> createPayOrder(@RequestBody CreatePayOrderRequestDTO dto) {

        try {

            if (StringUtils.isEmpty(dto.getUserId())) {
                dto.setUserId("测试用户");
            }

            // 创建订单
            PayOrderEntity order = orderService.createOrder(ShopCarEntity.builder()
                    .userId(dto.getUserId())
                    .productId(dto.getProductId())
                    .build());

            if (StringUtils.isNotBlank(order.getPayUrl())) {
                return Response.success(order.getPayUrl());
            }

            // 拉起支付
            PayChannelEnum payChannelEnum = PayChannelEnum.valueOf(dto.getPayChannel());
            CreatePayEntity createPayEntity = payServiceFactory.getPayResultService(payChannelEnum)
                    .orElseThrow(() -> new RuntimeException(ResponseCode.CREATE_PAY_FAIL.getInfo()))
                    .createPay(CreatePayReqEntity.builder()
                            .userId(order.getUserId())
                            .payChannelEnum(payChannelEnum)
                            .productId(dto.getProductId())
                            .productName(order.getProductName())
                            .orderId(order.getOrderId())
                            .totalAmount(order.getTotalAmount())
                            .build());

            // 更新订单支付信息
            PayOrderEntity prepareToPayOrder = orderService.prepareToPay(createPayEntity);

            return Response.success(prepareToPayOrder.getPayUrl());
        } catch (AlipayApiException e) {
            return Response.error(ResponseCode.CREATE_ORDER_FAIL);
        }
    }

    /**
     * 接收支付宝支付消息
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "alipay_notify_url", method = RequestMethod.POST)
    public String payNotify(HttpServletRequest request) throws Exception {
        Map<String, String[]> parameterMap = request.getParameterMap();
        log.info(JSONObject.toJSONString(parameterMap));
        payServiceFactory.getPayResultService(PayChannelEnum.ali_pay)
                .orElseThrow(() -> new RuntimeException(ResponseCode.ANALYSIS_PAY_RESULT_FAIL.getInfo()))
                .executePayResultHandel(request);
        return "success";
    }

}
